package cn.anecansaitin.firecrafting.common.util;

import net.minecraft.core.BlockPos;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;

import javax.annotation.Nullable;
import java.util.Random;
import java.util.function.Consumer;

//掉落物帮助类
public class DropHelper {
    private static final Random RANDOM = new Random();

    //在世界上生成物品掉落物，并可对掉落物实体进行编辑
    public static void dropItemStack(Level world, BlockPos pos, ItemStack stack, boolean consumed, @Nullable Consumer<ItemEntity> customEntity) {
        dropItemStack(world, pos.getX(), pos.getY(), pos.getZ(), stack, consumed, customEntity);
    }

    //在世界上生成物品掉落物，并可对掉落物实体进行编辑
    public static void dropItemStack(Level world, double x, double y, double z, ItemStack stack, boolean consumed, @Nullable Consumer<ItemEntity> customEntity) {
        double d0 = EntityType.ITEM.getWidth();
        double d1 = 1.0D - d0;
        double d2 = d0 / 2.0D;
        double d3 = Math.floor(x) + RANDOM.nextDouble() * d1 + d2;
        double d4 = Math.floor(y) + RANDOM.nextDouble() * d1;
        double d5 = Math.floor(z) + RANDOM.nextDouble() * d1 + d2;

        if (!consumed) {
            stack = stack.copy();
        }

        while (!stack.isEmpty()) {
            ItemEntity itementity = new ItemEntity(world, d3, d4, d5, stack.split(RANDOM.nextInt(21) + 10));
            float f = 0.05F;
            itementity.setDeltaMovement(RANDOM.nextGaussian() * (double) f, RANDOM.nextGaussian() * (double) f + (double) 0.2F, RANDOM.nextGaussian() * (double) f);

            if (customEntity != null) {
                customEntity.accept(itementity);
            }

            world.addFreshEntity(itementity);
        }
    }
}
